package org.goose.web;

import java.io.IOException;
import java.io.StringWriter;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.goose.web.models.User;
import org.goose.web.templates.TemplateFactory;

import com.oracle.xmlns.StMatthews.LoginProcess.LoginProcess.LoginProcessProxy;
import com.oracle.xmlns.StMatthews.LoginProcess.LoginProcess.ProcessResponse;

public class LoginHandler extends AbstractHandler{
	private static final Logger log = Logger.getLogger(LoginHandler.class);
	private User loggedIn;
	
	public LoginHandler(){
		loggedIn = null;
		//loggedIn = new User();
	}
	
	@Override
	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		if(loggedIn == null){
			if(request.getMethod().toString() == "POST"){
				if(validateLogin(request)){
					baseRequest.setHandled(true);
					response.sendRedirect("/");
					return;
				}else{
					baseRequest.setHandled(true);
					response.sendRedirect("");
				}
			}else{
				baseRequest.setHandled(true);
				returnLoginPage(response);
			}
		}
		
	}
	
	private void returnLoginPage(HttpServletResponse response){
		VelocityContext context = new VelocityContext();
		String t = null;
		t = "src/main/resources/velocity/login.vm";

		// 5. Merge Template
		Velocity.init();
		context.put("content", t);
		StringWriter sw = new StringWriter();
		Template layout = TemplateFactory.getTemplate("layout.vm");
		layout.merge(context, sw);

		// 6. Respond
		try {
			response.getWriter().println(sw);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private boolean validateLogin(HttpServletRequest request){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//Validation-Service client goes here.
		LoginProcessProxy proxy = new LoginProcessProxy();
		com.oracle.xmlns.StMatthews.LoginProcess.LoginProcess.Process payload = new com.oracle.xmlns.StMatthews.LoginProcess.LoginProcess.Process(username, password);
		ProcessResponse response = null;
		try {
			response = proxy.login(payload);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Temporary solution
		if(response.getRoleId() != -1) 
			loggedIn = new User(); 
		
		if(loggedIn == null) return false;
		return true;
	}
}
